const app = getApp();
import Toast from '../miniprogram_npm/@vant/weapp/toast/toast';
import Base64 from './Base64.js';
import CommonService from './service/commonService.js';
import Util from './util.js';

//token登录
function tokenLogin(inputObj,fromRepair,reportForm,reportSend,errorData,errorInside,fromCleanWork,equipmentElec,equipmentElecImei) {
  Toast.loading({
    duration: 0,
    forbidClick: true,
    message: '登录中...'
  });

  //用于审核，不走接口
  if(inputObj.userName=='account' && inputObj.password=='123456'){
    app.globalData.userInfo = {
      id: 363,
      depart: 585,
      departObj:[{
        name: "智能电子工牌",
        type: 4
      }],
      userName: "account",
      dataAuthorityOfUser:{
        depart: [639, 585, 959, 1802, 3563, 3565]
      },
      roles:[{"_id":"5ec247d2c863502744bcb6b8","id":9,"appId":[2,3,5],"dataAuthority":{"depart":[1,1],"type":[1,2,3,4,7]},"uiAuthOfRole":{"iot_tianjun":{"menuid":[""],"menu":{"equipmentList":{"list":{},"analysis":{}}}},"iot_admin":{"menuid":[93,79,88,80,83,96,97,122,124,126,125,153,154],"menu":{"equipment":{"base":{},"brandType":true,"memberType":true},"equipmentList":{"list":{},"analysis":{}},"baseInformation":{"SetEquipmentType":true,"SetEquipmentModel":true,"SetMountingsInformation":true},"OfficialAccountMaterial":{"VideoManagement":true},"systemManager":{"depart":{}}}},"iot_weapp":{"menu":{"iot":{"repairRecord":{"state":true,"callRecord":true,"revoke":true},"reportForm":true,"equipmentGroup":{"projectCount":true},"equipmentList":{"directPowerCheck":true,"directRecovery":true,"overhaul":true,"repair":true,"charge":true,"directStaticON":true,"iot":true,"direct":true,"edit":true,"region":true,"add":true,"check":true,"delete":true,"memberType":true,"project":true,"directStaticOFF":true,"directVibration":true,"exception":true,"train":true},"equipmentMap":true,"errorData":true,"exception":{}},"manage":{"location":true,"userList":true,"attendance":true,"attendanceTotal":true,"departList":{"add":true,"delete":true,"edit":true,"search":true},"enclosure":true,"equipmentScreen":true,"financialStatementsAll":true}},"menuid":[133,185,90,177,102,91,89,98,104,135,137,138,105,112,139,196]}},"dataAuthOfRole":{"key":"all_of_depart"},"roleName":"客户管理员","authority":{"product":{"openRecord":true},"financial":{"billPurchase":{},"billRent":{},"bill":true},"systemManager":{"invoice":{}},"vocher":{"vocherList":true},"dashboard":{"analysis":true},"order":{"purchase":{},"rent":{}}},"menuid":[4,5,44,13,14,16,15,20,19,18,25,26],"remark":"可查询本公司所有数据","state":1}]
    }
    wx.redirectTo({
      url: "/pages/equipmentList/equipmentList"
    })
  }else{
    let parameter = {
      userName:inputObj.userName,
      password:inputObj.password
    };

    let auth = Base64.encode(app.globalData.appAccount);
    let authHeader = {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Authorization': 'Basic ' + auth
    };

    const loginInfo = "grant_type=password" +
      "&username=" + inputObj.userName +
      "&password=" + inputObj.password;

    wx.request({
      url: app.globalData.tokenUrl,
      method:'post',
      header: authHeader,
      data: loginInfo,
      success:function(res){
        if(res.statusCode==200 && res.data.access_token){
          app.globalData.loginToken=res.data.access_token;
          console.log('token登录信息');
          console.log(res);

          //获取用户信息
          loginUserName(res.data.userName,parameter,fromRepair,reportForm,reportSend,errorData,errorInside,fromCleanWork,equipmentElec,equipmentElecImei);
        }else{
          Toast.fail(res.data.message);
        }
      },
      fail(){
        Toast.fail('请求数据资源服务错误');
      }
    })
  }
}

//获取用户信息
function loginUserName(userName,parameter,fromRepair,reportForm,reportSend,errorData,errorInside,fromCleanWork,equipmentElec,equipmentElecImei){
  let postParameter={
    userName: userName
  }

  CommonService.getUserByName(postParameter).then(res=>{
    Toast.clear();
    if(res.statusCode==200 && res.data.success==true){
			let user = res.data.data;
			console.log('登录');
			console.log(user);
			let dObj = user.departObj[0];

			//是否禁止登录（返回1禁止登录，返回2可以登录，返回3再查顶级部门）			
			if(dObj.level==1){
				//项级部门直接查自己
				isLogin(dObj.id).then(val => {
					if(val==1){
						Toast({
							type: 'fail',
							message: '您的账号异常暂不能登录',
							duration: 2000,
						});
					}else{
						//可正常登录
						loginEnter(user,userName,parameter,fromRepair,reportForm,reportSend,errorData,errorInside,fromCleanWork,equipmentElec,equipmentElecImei);
					}
				});
			}else{
				//大区（先查自己，未设置再查顶级部门）
				if(dObj.isRegion){
					isLogin(dObj.id).then(val => {
						if(val==1){
							Toast({
								type: 'fail',
								message: '您的账号异常暂不能登录',
								duration: 2000,
							});
						}else if(val==2){
							//可正常登录
							loginEnter(user,userName,parameter,fromRepair,reportForm,reportSend,errorData,errorInside,fromCleanWork,equipmentElec,equipmentElecImei);
						}else if(val==3){
							isLogin(dObj.companyId).then(val => {
								if(val==1){
									Toast({
										type: 'fail',
										message: '您的账号异常暂不能登录',
										duration: 2000,
									});
								}else{
									//可正常登录
									loginEnter(user,userName,parameter,fromRepair,reportForm,reportSend,errorData,errorInside,fromCleanWork,equipmentElec,equipmentElecImei);
								}
							});
						}
					});
				}else{
					//项目登录（先查大区，大区未设置再查顶级部门）
					if(dObj.regionId!=null){		
						isLogin(dObj.regionId).then(val => {
							if(val==1){
								Toast({
									type: 'fail',
									message: '您的账号异常暂不能登录',
									duration: 2000,
								});
							}else if(val==2){
								//可正常登录
								loginEnter(user,userName,parameter,fromRepair,reportForm,reportSend,errorData,errorInside,fromCleanWork,equipmentElec,equipmentElecImei);
							}else if(val==3){
								isLogin(dObj.companyId).then(val => {
									if(val==1){
										Toast({
											type: 'fail',
											message: '您的账号异常暂不能登录',
											duration: 2000,
										});
									}else{
										//可正常登录
										loginEnter(user,userName,parameter,fromRepair,reportForm,reportSend,errorData,errorInside,fromCleanWork,equipmentElec,equipmentElecImei);
									}
								});
							}
						});
					}else{
						isLogin(dObj.companyId).then(val => {
							if(val==1){
								Toast({
									type: 'fail',
									message: '您的账号异常暂不能登录',
									duration: 2000,
								});
							}else{
								//可正常登录
								loginEnter(user,userName,parameter,fromRepair,reportForm,reportSend,errorData,errorInside,fromCleanWork,equipmentElec,equipmentElecImei);
							}
						});
					}
				}
			}
    }else{
      Toast.fail('用户名或密码错误');
    }
  }).catch((error) => {
  })
}

//登录后操作
function loginEnter(user,userName,parameter,fromRepair,reportForm,reportSend,errorData,errorInside,fromCleanWork,equipmentElec,equipmentElecImei){
	let dObj = user.departObj[0];

	//处理客户权限（客户，厂家，页面里遇到判断这两个类型时用到，其他类型还是用type）
	let multiType=[];
	if(dObj.multiType){
		multiType=dObj.multiType;
	}

	let type2Flag=multiType.some(item=>{
		return item==2
	});
	let type4Flag=multiType.some(item=>{
		return item==4
	});

	if(dObj.type==2 || type2Flag){
		user.typeHandle=2;
	}
	if(dObj.type==4 || type4Flag){
		user.typeHandle=4;
	}

	console.log('用户登录信息');
	console.log(user);
	app.globalData.userInfo = user;

	let roles = user.roles;
	if (roles.length) {
		//获取用户权限
		getAuthority();

		//将用户名密码存入本地
		try {
			let arrs=[];
			let flag=false;
			let loginInputArr=wx.getStorageSync('loginInputNew');

			//比较原存储数组和输入数据
			if(loginInputArr && loginInputArr.length){
				loginInputArr.forEach(item => {
					if(item.userName!=parameter.userName){
						arrs.push(item);
					}else if((item.userName==parameter.userName) && (item.password!=parameter.password)){
						flag=true;
					}
				});
			}

			if(!flag){
				arrs.push(parameter);
			}
			wx.setStorageSync("loginInputNew",arrs);
			wx.setStorageSync("loginInputLast",parameter);
		} catch (e) { }

		//日志
		loginLog();

		//如果是从公众号页面跳转来的，登录后转到相应页面（报修，报表，异常数据，保洁工单，低电列表）
		if (fromRepair) {
			wx.redirectTo({
				url: "/pages/repairAdd/repairAdd"
			})
		} else if(reportForm){
			wx.redirectTo({
				url: "/pages/reportForm/reportForm"
			})
		} else if(reportSend){
			wx.redirectTo({
				url: "/packageA/pages/reportSend/reportSend"
			})
		}else if(errorData){
			wx.redirectTo({
				url: "/packageA/pages/errorData/errorData"
			})
		}else if(errorInside){
			wx.redirectTo({
				url: "/packageA/pages/errorDataInside/errorDataInside"
			})
		}else if(fromCleanWork){
			wx.redirectTo({
				url: "/packageA/pages/cleanWorkList/cleanWorkList"
			})
		}else if(equipmentElec){
			wx.redirectTo({
				url: "/pages/equipmentListElec/equipmentListElec?imei="+equipmentElecImei
			})
		}else{
			//超级管理员跳转分组，其他跳转个人中心
			if(user.role.indexOf(3)==-1){
				wx.redirectTo({
					url: "/pages/personalCenter/personalCenter"
				})
			}else{
				wx.redirectTo({
					url: "/pages/equipmentGroup/equipmentGroup"
				})
			}

			//测试用
			// wx.redirectTo({
			//   url: "/packageA/pages/dataCollector/dataCollector"
			// })
		}

	}else {
		Toast.fail('未分配权限，请联系平台管理员');
	}
}

//获取用户权限
function getAuthority(){
  let user=app.globalData.userInfo;
  let roles=user.roles;
  let roleArr=[];

  roles.forEach(item=>{
    if(item.uiAuthOfRole.iot_weapp){
      roleArr.push(item);
    }
  });

  let authority={};
  roleArr.forEach(item=>{
    DeepAssign(authority,item.uiAuthOfRole.iot_weapp.menu);
  });

  console.log('用户权限');
  console.log(authority);

  app.globalData.authority=authority;
}

//处理角色权限
function DeepAssign(object1,object2) {
  let keys1=Object.keys(object1);
  let keys2=Object.keys(object2);
  let unionkeys = keys1.concat(keys2.filter(v => !keys1.includes(v)));
  unionkeys.forEach(key=>{
    //如果两个对象该字段都有值
    if(object1[key]&&object2[key]){
      //如果对象1为true则无需再向下判断直接等于对象2的值
      if(object1[key]==true){
        object1[key]=object2[key];
      }else if(object2[key]!=true){//如果对象1是个对象类型对象二也是对象类型,则递归调用该方法判断
        DeepAssign(object1[key],object2[key]);
      }
    }else if(object2[key]){
      object1[key]=object2[key];
    }
  })
}

//验证顶级部门是否可登录
function isLogin(id){
	let param={
		isAuth: false,
		className: 'depart',
		data:{
			id: id,
			nbl: Base64.encode(Util.timeFormatDay(new Date())),
			selectFields: ['id','loginDisable']
		}
	}

	return new Promise((resolve, reject) => {
		CommonService.goFindList(param).then(res=>{
			console.log('是否可登录');
			console.log(res);

			if (res.data.data && res.data.data.result && res.data.data.result.length) {
				let result = res.data.data.result[0];
				if(result.loginDisable!=null){
					if(result.loginDisable){
						resolve(1);
					}else{
						resolve(2);
					}
				}else{
					resolve(3);
				}
			}else{
				resolve(3);
			}
		}).catch((error) => {
			resolve(3);
		})
	});
}

//日志
function loginLog(){
	let pages = getCurrentPages();
  let lastPage = pages[pages.length - 1];
		
	let param={
		logTitle: '登录',
		function: lastPage.route,
		state: 1
	}	

	CommonService.operateLogSave(param).then(res=>{
	}).catch((error) => {
	})	
}

module.exports = {
  tokenLogin: tokenLogin,
  loginUserName: loginUserName
}
